import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { FormInstance } from 'antd/lib/form';
import { Modal, Button, message, Input, Form, Select,} from 'antd';
import {getDictOptionsByCode } from '@/support/common';
import PropTypes from 'prop-types';

const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
  basedata: state.basedata,
  goodAttribute: state.goodAttribute,
});
class AddModal extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();

  static contextTypes = {
    dicData: PropTypes.any,
  };
  constructor(props: any) {
    super(props);
    this.state = {
      brandOptions:[],
      goodsTypeOptions:[],
    };
  }
  componentDidUpdate(prevProps: any) {
    const { modalVisible, record,isAdd,dispatch } = this.props
    if (record && !isAdd && modalVisible && modalVisible !== prevProps.modalVisible) {
      console.log('record', record)
      dispatch({
        type: 'goodAttribute/postObjWithRes',
        payload: {url:'/optshop/base/goodstype/searchAll',  brandId: record.brandId },
        callback: (response:any) => {
          if (response) {
            this.setState({
              goodsTypeOptions: response.data.list.map((item:any)=>{
                return {
                  label: item.goodsTypeName,
                  value: item.goodsTypeId
                }
               }),
            });
          } else {
            this.setState({
              goodsTypeOptions: [],
            });
          }
        },
      });
      this.formRef && this.formRef.current?.setFieldsValue({
        ...record
      })
    }
  }
  componentWillMount() {
    //品牌信息查询
    this.props.dispatch({
      type: 'basedata/brandFetch',
      callback: (res:any) => {
        this.setState({ 
           brandOptions: res?.data?.map((item:any)=>{
            return {
              label: item.brandName,
              value: item.brandCode
            }
           }),
        });
       }
    })
  }
  submitForm = () => {
    this.formRef.current?.submit();
  };
  ok = (values: any) => {
    const { dispatch,isAdd,record } = this.props;
    let params = {};
    if(isAdd){
      params={
        ...values,
        brandId: values.brandId.value,
        brandName:  values.brandId.label,
      }
    }else{
      params={
        ...values,
        brandId: values.brandId.value,
        brandName:  values.brandId.label,
        sid: record.sid,
      }
    }
    dispatch({
      type: 'goodAttribute/postObjWithRes',
      payload: {
        url: isAdd ? '/optshop/base/subsidiary/attribute/save' : '/optshop/base/subsidiary/attribute/update',//待修改url
        ...params
      },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          this.close();
          isAdd ? message.success('新增成功') : message.success('编辑成功');
          const params={
            current: 1, pageSize: 10,
          }
          dispatch({
            type: 'goodAttribute/postFetchPage',
            payload: { url: '/optshop/base/subsidiary/attribute/search', ...params,},
          });
        }
      },
    });
  };

  close = () => {
    this.formRef.current?.resetFields();
    const { closeModal } = this.props;
    closeModal();
  };
  
  onBrandSelect = (value:any) => {
    //通过品牌查询商品类型
    this.formRef.current?.setFieldsValue({ goodsTypeId: '',});
    // if (value) {
      this.props.dispatch({
        type: 'goodAttribute/postObjWithRes',
        payload: {url:'/optshop/base/goodstype/searchAll',  brandId: value.value },
        callback: (response:any) => {
          if (response) {
            this.setState({
              goodsTypeOptions: response.data.list.map((item:any)=>{
                return {
                  label: item.goodsTypeName,
                  value: item.goodsTypeId
                }
               }),
            });
          } else {
            this.setState({
              goodsTypeOptions: [],
            });
          }
        },
      });
  }
  render() {
    const { modalVisible, loading, isAdd } = this.props;
    const { brandOptions, goodsTypeOptions} = this.state;
    const unitOptions = getDictOptionsByCode(this.context.dicData, 'unit');
    const footer = (
      <div>
        <Button size="small" onClick={this.close}>
          取消
        </Button>
        <Button size="small" loading={loading} onClick={this.submitForm} type="primary">
          保存
        </Button>
      </div>
    );
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 8 },
        md: { span: 16 },
      },
    };
    return (
      <Modal
        style={{ top: 20 }}
        footer={footer}
        title={isAdd ? "创建附属属性" : "编辑附属属性"}
        visible={modalVisible}
        onCancel={this.close}
      >
        <Form style={{ marginTop: 12 }} ref={this.formRef} onFinish={this.ok}>
          <FormItem
            {...formItemLayout}
            label="品牌"
            name="brandId"
            rules={[{ required: true, message: '请选择品牌' }]}
          >
            <Select 
            placeholder="请选择品牌"
            disabled={!isAdd}
            getPopupContainer={triggerNode => triggerNode.parentNode} 
            options={brandOptions}
            onChange={this.onBrandSelect}
            labelInValue/>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="商品类型"
            name="goodsTypeId"
            rules={[{ required: true, message: '请选择商品类型' }]}
          >
            <Select 
            placeholder="请选择商品类型"
            disabled={!isAdd}
            getPopupContainer={triggerNode => triggerNode.parentNode} 
            options={goodsTypeOptions} />
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="属性名称"
            name="skuAttributeName"
            rules={[{ required: true, message: '请输入属性名称' }]}
          >
            <Input placeholder="请输入属性名称" maxLength={40}/>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="属性代码"
            name="skuAttributeCode"
            rules={[{ required: true, message: '请输入属性代码' }]}
          >
            <Input placeholder="请输入属性代码" maxLength={20}  disabled={!isAdd}/>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="单位"
            name="unit"
            rules={[{ required: true, message: '请选择单位' }]}
          >
            <Select 
            placeholder="请选择单位"
            disabled={!isAdd}
            getPopupContainer={triggerNode => triggerNode.parentNode} 
            options={unitOptions} />
          </FormItem>
        </Form>
      </Modal>
    );
  }
}
export default connect(mapStateToProps)(AddModal);
